package br.com.beautycenter.hibernateUtil;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;


public class DaoBase<T extends Serializable> {
    
    @PersistenceContext(unitName="ERPBeautyCenterJPA")
    private final EntityManager em;
    private final Class<T> persisteClass;
    
    public DaoBase() {
        this.em = EntityManagerUtil.getEntityManager();
        this.persisteClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
    
    public  EntityManager getEntityManager() {
        return em;
    }
    
    protected boolean save(T entity) {
        EntityTransaction tx = getEntityManager().getTransaction();

        try {
            tx.begin();
            getEntityManager().persist(entity);
            tx.commit();
            
            return true;
            
        } catch (Throwable t) {
            System.out.println("erro: " + t.getMessage());
            tx.rollback();
            return false;
        }
        
    }
    
    protected void update(T entity) {
        EntityTransaction tx = getEntityManager().getTransaction();

        try {
            tx.begin();
            getEntityManager().merge(entity);
            tx.commit();
        } catch (Throwable t) {
            t.printStackTrace();
            tx.rollback();
        }
    }
    
    protected void refresh(){
        getEntityManager().getEntityManagerFactory().getCache().evictAll();
    }
    
    protected boolean delete(T entity) {
        EntityTransaction tx = getEntityManager().getTransaction();

        try {
            tx.begin();
            getEntityManager().remove(entity);
            tx.commit();
            return true;
        } catch (Throwable t) {
            tx.rollback();
            return false;
        } 
    }
    
    public List<T> findAll() throws Exception {
        Session session = (Session) getEntityManager().getDelegate();
        return session.createCriteria(persisteClass).list();
    }
    
    private void close() {
        if (getEntityManager().isOpen()) {
            getEntityManager().close();
        }
    }
        
}